package subumbo.leg.service
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import org.osflash.signals.Signal;
	import org.robotlegs.mvcs.Actor;
	
	/**
	 * Base class for services that load assets. It encapsulates a flash Loader instance and dispatches a progress and loaded Signal. 
	 * @author pwolleb
	 * 
	 */	
	public class AssetService extends Actor implements IService
	{
		protected var _request:URLRequest = new URLRequest();
		protected var _context:LoaderContext = new LoaderContext();
		public var loadedSignal:Signal = new Signal();
		public var progressSignal:Signal = new Signal(Number);
		
		public function send():void {
			_context.applicationDomain = ApplicationDomain.currentDomain;
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onResult, false, 0 ,true);
			loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress, false, 0 ,true);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0 ,true);
			loader.load(_request, _context);
		}
		
		protected function onResult(e:Event):void {
			e.stopImmediatePropagation();
			var loaderInfo:LoaderInfo = LoaderInfo(e.target);
			loaderInfo.removeEventListener(Event.COMPLETE, onResult);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			loaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loadedSignal.dispatch();
		}
		
		protected function onProgress(e:ProgressEvent):void {
			progressSignal.dispatch(e.bytesTotal / e.bytesLoaded * 100);
		}
		
		protected function onIOError(e:IOErrorEvent):void {
			trace("AssetService::onIOError \n URL: " + e.text );;
		}
		
		public function get context():LoaderContext {
			return _context;
		}
		
		public function set context(val:LoaderContext):void {
			_context = val;
		}
		
		public function set request(val:URLRequest):void {
			_request = val;
		}
		
		public function get request():URLRequest {
			return _request;
		}
		
	}
}